﻿using WQLWebAPI.Infrastructure.CommonDtos;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WQLWebAPI.Infrastructure.Extensions
{
    public static class EpplusHelper
    {

        public static byte[] GetImageByte(ExcelPicture picture)
        {

            using (MemoryStream ms = new MemoryStream())
            {
                picture.Image.Save(ms, picture.ImageFormat);

                return ms.ToArray();
            }
        }
        public static Image GetImage(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                return Image.FromStream(ms);
            }
        }



        /// <summary>
        /// 获取表格中带图片的内容:注意文字是从1开始，图片是从0开始
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="row">文字行从0开始</param>
        /// <param name="col">文字列从0开始</param>
        /// <returns></returns>
        public static ExcelContentDto GetExcelContent(this ExcelWorksheet worksheet, int row, int col)
        {

            ExcelContentDto result = new ExcelContentDto();
            var temp = worksheet.Drawings[0];
            var Images = worksheet.Drawings.Where(d => d.From.Row == row-1 && d.From.Column == col-1).Select(g => g as ExcelPicture).ToList();

            if (Images.Count == 0)
            {
                result.Content = worksheet.Cells[row, col ].GetValue<string>();

            }
            else
            {
                result.Content = worksheet.Cells[row , col ].GetValue<string>();
                result.Images = new List<byte[]>();
                for (int i = 0; i < Images.Count; i++)
                {
                    if(Images[i]!=null) result.Images.Add(GetImageByte(Images[i]));


                }
            }

            return result;
        }
        public static T GetMergeValue<T>(this ExcelWorksheet wSheet, int row, int column)
        {
            var range = wSheet.MergedCells[row, column];
            if (range == null)
            {
                return wSheet.Cells[row, column].GetValue<T>();
            }
            else
            {

                return wSheet.Cells[(new ExcelAddress(range)).Start.Row, (new ExcelAddress(range)).Start.Column].GetValue<T>();
            }
        }

        public static ExcelAddress GetMergeRange(this ExcelWorksheet wSheet, int row, int column)
        {
            var range = wSheet.MergedCells[row, column];
            if (range == null)
            {
                return wSheet.Cells[row, column];
            }
            else
            {

                return new ExcelAddress(range);
            }
        }

    }
}
